//
//  ScannerProtocal.swift
//  GreenDeal
//
//  Created by Moennig Q on 15/11/2022.
//

import UIKit
import AVFoundation
struct ScanningResult {
    var barcode: String = ""
    // code 类型 Code 128等
    var type: String = ""
    //识别时间
    var scanTime: Int32 = 0
    //带绿色表示线的图片
    var imageData: Data? = nil
    //可信度
    var confidence: Int32 = 0
    //
    var realBarcode: String {
        return barcode.replacingOccurrences(of: ",", with: "")
    }
}
enum ScanMode: Int{
    case oneD = 1//一维码
    case qrCODE = 2//二维码
}

enum ScanAddMethodMode: String{
    case manually = "Manually"//手动增加
    case auto = "Auto"//扫描增加
}
protocol ScannerViewProtocal where Self: UIView{
    // MARK: - 是否正在扫描识别
    var isScanning: Bool { get set}
    // MARK: - 当前识别方式
    var scanAddMethodMode: ScanAddMethodMode { get set}
    // MARK: - 条形码模式还是二维码模式
    var scanMode: ScanMode { get set}
    //MARK: - 是否可以识别反色条码
    var enableInvertedBarcodeFlag: Bool { get set}
    // MARK: - Manully点击takePhoto的回调
    var takePhotoResultClosure: ((Data)->Void)? { get set}
    // MARK: - 获取扫描识别的结果（auto，manually都用到）
    var scanResultClosure: ((ScanningResult)->Void)? { get set}
    // MARK: - 启动扫描器
    func launchScanner(enableInvetedFlag: Bool,enableFuzzyFlag: Bool)
    // MARK: - 开始扫描
    func startScanning()
    // MARK: - 停止扫描
    func stopScanning()
    // MARK: - 切换是否扫描反色条码
    func switchInverterSetting(_: Bool)
    // MARK: - 切换是否开启模糊扫码设置
    func switchFuzzyScanSetting(_: Bool)
    // MARK: - 切换二维码或一维码
    func switchScanMode(_: ScanMode)
    // MARK: - 拍照
    func takePhoto()
    //MARK: - 清空手动上次识别的内容
    func clearPreResultForManually()
    // MARK: - 释放扫描器
    func releaseScanner()
    //MARK:  - 解码当前时间
    var decodeCurrentTime: Date {get set}
}
extension ScannerViewProtocal {
    // MARK: - 切换是否打开闪光灯
    func switchTorchMode()->Bool{
        guard let device = AVCaptureDevice.default(for: AVMediaType.video) else{
            return false
        }
        var enableFlag: Bool = false
        if device.hasTorch {
            do {
                try device.lockForConfiguration()
            } catch {
                debugPrint(error)
            }
            device.torchMode = (device.torchMode == .on) ? .off : .on
            enableFlag = (device.torchMode == .on) ? true : false
            device.unlockForConfiguration()
        }
        return enableFlag
    }
    //检查是否有可用的后置摄像头
    func checkIfHaveAvailableDevice()->Bool{
        if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerController.CameraDevice.rear) && UIImagePickerController.isSourceTypeAvailable(.camera){
            return true
        }
        return false
    }
}
